package com.yhh.common.jwt;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yhh.common.base.ret.ApiResult;
import com.yhh.common.entity.member.model.User;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *  基于 JWT 生成和解析 token 工具
 */
public class JWTUtil {
    // 生成 token 的密钥
    public static final String SECRET="yhh";
    // token 的有效时间(7 day)
    public static final int TOKEN_EXP = 1000*60*60*24*7;
    /**
     *  生成token
     * @param user
     * @return
     */
    public static ApiResult createToken(User user){
        Map<String, Object> map = new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");

        try {
            String token = JWT.create().withHeader(map)
                    .withClaim("iss","Server")//签发人
                    .withClaim("aud","APP")//受众
                    .withClaim("user", user  == null ?"":JSON.toJSONString(user))//自定义字段
                    .withIssuedAt(new Date())
                    .withExpiresAt(new Date(System.currentTimeMillis()+TOKEN_EXP))
                    .sign(Algorithm.HMAC256(SECRET));//签名
            return ApiResult.success().put("token",token);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("创建token失败");
        }
    }
    /**
     * 验证token 并返回用户对象信息
     * @param token
     * @return
     */
    public static ApiResult verifyToken(String token){
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);

            // 获取token里面的信息
            if(jwt == null || jwt.getClaim("user") == null || "".equalsIgnoreCase(jwt.getClaim("user").asString())){
                return ApiResult.error("用户登录信息验证失败");
            }
            return ApiResult.success().put("user",jwt.getClaim("user").asString());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return ApiResult.error("登录凭证参数非法");
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return ApiResult.error("登录凭证已过期，请重新登录");
        } catch (Exception e){
            e.printStackTrace();
            return ApiResult.error(e.getMessage());
        }
    }
}
